package lock.atomic;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * @author Brook
 */
public class AtomicArrayDemo {
    public static void main(String[] args) throws InterruptedException {
        AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(1000);

        Incrementer incrementer = new Incrementer(atomicIntegerArray);
        Decrementer decrementer = new Decrementer(atomicIntegerArray);

        Thread[] threadsIncrement = new Thread[100];
        Thread[] threadsDecrement = new Thread[100];
        for (int i = 0; i < 100; i++) {
            Runnable target;
            threadsDecrement[i] = new Thread(decrementer);
            threadsIncrement[i] = new Thread(incrementer);
            threadsDecrement[i].start();
            threadsIncrement[i].start();
        }

        for (int i = 0; i < 100; i++) {
            threadsDecrement[i].join();
            threadsIncrement[i].join();
        }

        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            if (atomicIntegerArray.get(i)!=0) {
                System.out.println("发生了错误"+i);
            }
            System.out.println(atomicIntegerArray.get(i));
        }
        System.out.println("运行结束");
    }

}

class Decrementer implements Runnable {

    private AtomicIntegerArray atomicIntegerArray;

    public Decrementer(AtomicIntegerArray atomicIntegerArray){
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            atomicIntegerArray.getAndDecrement(i);
        }
    }
}

class Incrementer implements Runnable {

    private AtomicIntegerArray atomicIntegerArray;

    public Incrementer(AtomicIntegerArray atomicIntegerArray){
        this.atomicIntegerArray = atomicIntegerArray;
    }

    @Override
    public void run() {
        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            atomicIntegerArray.getAndIncrement(i);
        }
    }
}